Letter Combinations of a Phone Number

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Letter Combinations of a Phone Number - 图1

  1. Input:Digit string "23"
  2. Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

Solution:

  1. public class Solution {
  2. public List<String> letterCombinations(String digits) {
  3. String[] keyboard = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
  4. List<String> res = new ArrayList<String>();
  5. helper(digits, keyboard, 0, "", res);
  6. return res;
  7. }
  8. private void helper(String digits, String[] keyboard, int index, String sol, List<String> res) {
  9. if (sol.length() == digits.length()) {
  10. res.add(sol);
  11. return;
  12. }
  13. int idx = (int)(digits.charAt(index) - '0');
  14. String key = keyboard[idx];
  15. for (int i = 0; i < key.length(); i++) {
  16. helper(digits, keyboard, index + 1, sol + key.charAt(i), res);
  17. }
  18. }
  19. }